package controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import view.TeamView;
import bo.Player;
import bo.PlayerCareerStats;
import bo.PlayerSeason;
import bo.Team;
import bo.TeamSeason;
import bo.TeamSeasonPlayer;
import dataaccesslayer.HibernateUtil;

public class TeamController extends BaseController {
	@Override
    public void init(String query) {
        System.out.println("building dynamic html for team");
        view = new TeamView();
        process(query);
    }
    
    @Override
    protected void performAction() {
        String action = keyVals.get("action");
        System.out.println("teamcontroller performing action: " + action);
        if (action.equalsIgnoreCase(ACT_SEARCHFORM)) {
            processSearchForm();
        } else if (action.equalsIgnoreCase(ACT_SEARCH)) {
            processSearch();
        } else if (action.equalsIgnoreCase(ACT_DETAIL)) {
            processDetails();
        } else if (action.equalsIgnoreCase(ACT_ROSTER)) {
            processRoster();
        } else if (action.equalsIgnoreCase(ACT_LINK)) {
            processLink();
        }
    }

    protected void processSearchForm() {
        view.buildSearchForm();
    }
    
    protected final void processSearch() {
        String name = keyVals.get("name");
        if (name == null) {
			System.out.println("name is null in processSearch");
            return;
        }
        String v = keyVals.get("exact");
        boolean exact = (v != null && v.equalsIgnoreCase("on"));
        List<Team> bos = HibernateUtil.retrieveTeamsByName(name, exact);
        view.printSearchResultsMessage(name, exact);
        buildSearchResultsTableTeam(bos);
        view.buildLinkToSearch();
    }
    
    protected final void processLink() {
        String id = keyVals.get("id");
        if (id == null) {
			System.out.println("id is null in processLink");
            return;
        }
        Team t = HibernateUtil.retrieveTeamById(Integer.valueOf(id));
        if (t == null) {
			System.out.println("Team not found in processLink by id: " + id);
			return;
		}
        List<Team> bos = new ArrayList<Team>();
        bos.add(t);
        buildSearchResultsTableTeam(bos);
        view.buildLinkToSearch();
    }

    protected final void processDetails() {
        String id = keyVals.get("id");
        if (id == null) {
			System.out.println("id is null in processDetails");
            return;
        }
        Team t = (Team) HibernateUtil.retrieveTeamById(Integer.valueOf(id));
        if (t == null) {
			System.out.println("Team not found in processDetails by id: " + id);
			return;
		}
        buildSearchResultsTableTeamDetail(t);
        view.buildLinkToSearch();
    }
    
    protected final void processRoster() {
        String id = keyVals.get("id");
        String year = keyVals.get("year");
        if (id == null) {
			System.out.println("id is null in processDetails");
            return;
        } else if (year == null) {
        	System.out.println("year is null in processDetails");
            return;
        }
        Team t = (Team) HibernateUtil.retrieveTeamById(Integer.parseInt(id));
        if (t == null) {
			System.out.println("Team not found in processRoster by id: " + id);
			return;
		}
        buildSearchResultsTableTeamRoster(t, Integer.parseInt(year));
        view.buildLinkToSearch();
    }

    private void buildSearchResultsTableTeam(List<Team> bos) {
        // need a row for the table headers
        String[][] table = new String[bos.size() + 1][5];
        table[0][0] = "Id";
        table[0][1] = "Name";
        table[0][2] = "League";
        table[0][3] = "Year Founded";
        table[0][4] = "Most Recent Year";
        for (int i = 0; i < bos.size(); i++) {
            Team t = bos.get(i);
            String tid = Integer.toString(t.getTeamId());
            table[i + 1][0] = view.encodeLink(new String[]{"id"}, new String[]{tid}, tid, ACT_DETAIL, SSP_TEAM);
            table[i + 1][1] = t.getName();
            table[i + 1][2] = t.getLeague();
            table[i + 1][3] = Integer.toString(t.getYearFounded());
            table[i + 1][4] = Integer.toString(t.getYearLast());
        }
        view.buildTable(table);
    }
    
    private void buildSearchResultsTableTeamDetail(Team t) {
    	Set<TeamSeason> seasons = t.getSeasons();
    	List<TeamSeason> list = new ArrayList<TeamSeason>(seasons);
    	Collections.sort(list, TeamSeason.teamSeasonsComparator);
    	// build 2 tables.  first the team details, then the season details
        // need a row for the table headers
        String[][] playerTable = new String[2][4];
        playerTable[0][0] = "Name";
        playerTable[0][1] = "League";
        playerTable[0][2] = "Year Founded";
        playerTable[0][3] = "Most Recent Year";
        playerTable[1][0] = t.getName();
        playerTable[1][1] = t.getLeague();
        playerTable[1][2] = Integer.toString(t.getYearFounded());
        playerTable[1][3] = Integer.toString(t.getYearLast());
        view.buildTable(playerTable);
        // now for seasons
        String[][] seasonTable = new String[seasons.size()+1][7];
        seasonTable[0][0] = "Year";
        seasonTable[0][1] = "Games Played";
        seasonTable[0][2] = "Roster";
        seasonTable[0][3] = "Wins";
        seasonTable[0][4] = "Losses";
        seasonTable[0][5] = "Rank";
        seasonTable[0][6] = "Attendance";
        int i = 0;
        for (TeamSeason ps: list) {
        	i++;
        	String year = Integer.toString(ps.getYear());
        	String id = Integer.toString(t.getTeamId());
        	seasonTable[i][0] = year;
        	seasonTable[i][1] = Integer.toString(ps.getGamesPlayed());
        	seasonTable[i][2] = view.encodeLink(new String[]{"id", "year"}, new String[]{id, year}, "Roster", ACT_ROSTER, SSP_TEAM);
        	seasonTable[i][3] = Integer.toString(ps.getWins());
        	seasonTable[i][4] = Integer.toString(ps.getLosses());
        	seasonTable[i][5] = Integer.toString(ps.getRank());
        	seasonTable[i][6] = Integer.toString(ps.getTotalAttendance());
        }
        view.buildTable(seasonTable);
    }
    
    private void buildSearchResultsTableTeamRoster(Team t, int year) {
    	Set<TeamSeasonPlayer> teamSeasonPlayers = t.getTeamSeasonPlayerByYear(year);
    	List<Player> players = new ArrayList<Player>();
    	for (TeamSeasonPlayer tsp: teamSeasonPlayers) {
    		players.add(tsp.getPlayer());
    	}
    	System.out.println("building roster");
    	// build 2 tables.  first the team details, then the season details
        // need a row for the table headers
        String[][] playerTable = new String[2][4];
        playerTable[0][0] = "Name";
        playerTable[0][1] = "League";
        playerTable[0][2] = "Year";
        playerTable[0][3] = "Player Payroll";
        playerTable[1][0] = t.getName();
        playerTable[1][1] = t.getLeague();
        playerTable[1][2] = Integer.toString(year);
        // now for seasons
        String[][] seasonTable = new String[players.size()+1][3];
        seasonTable[0][0] = "Name";
        seasonTable[0][1] = "Games Played";
        seasonTable[0][2] = "Salary";
        int i = 0;
        double totalSalaries = 0;
        for (Player p: players) {
        	PlayerSeason ps = p.getPlayerSeason(year);
        	i++;
        	String name = p.getName();
        	seasonTable[i][0] = view.encodeLink(new String[]{"id"}, new String[]{p.getId().toString()}, name, ACT_LINK, SSP_PLAYER);
        	if (ps != null) {
	        	String gamesPlayed = ps.getGamesPlayed().toString();
	        	double money = ps.getSalary();
	        	String salary = "$" + Double.toString(money);
	        	seasonTable[i][1] = gamesPlayed;
	        	seasonTable[i][2] = salary;
	        	totalSalaries += money;
        	} else {
        		seasonTable[i][1] = "";
	        	seasonTable[i][2] = "";
        	}
        }
        playerTable[1][3] = "$" + Double.toString(totalSalaries);
        view.buildTable(playerTable);
        view.buildTable(seasonTable);
    }
}
